<?php
// +---------------------------------------------------------------------+
// | NiuCloud | [ WE CAN DO IT JUST NiuCloud ]                |
// +---------------------------------------------------------------------+
// | Copy right 2019-2029 www.niucloud.com                          |
// +---------------------------------------------------------------------+
// | Author | NiuCloud <niucloud@outlook.com>                       |
// +---------------------------------------------------------------------+
// | Repository | https://github.com/niucloud/framework.git          |
// +---------------------------------------------------------------------+

namespace addon\wxoplatform\model;


use addon\wechat\model\Wechat;
use EasyWeChat\Factory;
use app\model\BaseModel;
use EasyWeChat\OpenPlatform\Server\Guard;
use EasyWeChat\OpenPlatform\Auth\VerifyTicket;
use think\facade\Cache;

/**
 * 微信开放平台
 */
class Oplatform extends BaseModel
{

    private $app;//微信公众对象


    public function __construct($site_id = 0)
    {
        $config_model = new Config();
        $config_result = $config_model->getOplatformConfig($site_id);
        $config = $config_result["data"];
        if (!empty($config)) {
            $config_info = $config["value"];
        }

        $config = [
            'app_id' => $config_info["appid"] ?? '',
            'secret' => $config_info["secret"] ?? '',
            'token' => $config_info["token"] ?? '',
            'aes_key' => $config_info["aes_key"] ?? '',

            'log' => [
                'level' => 'debug',
                'permission' => 0777,
                'file' => 'runtime/log/wechat/oplatform.logs',
            ],
        ];
        $this->app = Factory::openPlatform($config);
//        $response = $this->app->server->serve();
        // 将响应输出
//        $response->send();exit; // Laravel 里请使用：return $response;
    }

    /**
     * 开放平台获取授权
     * @param $param
     * @return \EasyWeChat\OpenPlatform\Authorizer\MiniProgram\Account\Client|\EasyWeChat\OpenPlatform\Authorizer\OfficialAccount\Account\Client
     */
    public function app($param)
    {
        if ($param["type"] == "wechat") {
            // 代公众号实现业务
            $officialAccount = $this->app->officialAccount($param["authorizer_appid"], $param["authorizer_refresh_token"] ?? null);
            $account = $officialAccount;
        } else {
            // 代小程序实现业务
            $miniProgram = $this->app->miniProgram($param["authorizer_appid"], $param["authorizer_refresh_token"] ?? null);
            $account = $miniProgram;
        }
        return $account;
    }


    /**
     * 获取用户授权页 URL
     * @param $param
     * @return array
     */
    public function getPreAuthorizationUrl($param = [])
    {
        try {
            $result = $this->app->getPreAuthorizationUrl($param['callback']);
            return $this->success($result);
        } catch (\Exception $e) {
            return $this->error([], $e->getMessage());
        }
    }

    /**
     * 使用授权码换取接口调用凭据和授权信息
     * @param $param
     * @return array
     */
    public function handleAuthorize($param = [])
    {
        try {
            $code = $param["code"] ?? null;
            $result = $this->app->handleAuthorize($code);
            if (isset($result['errcode']) && $result['errcode'] != 0) {
                return $this->error($result, $result["errmsg"]);
            }
            return $this->success($result);
        } catch (\Exception $e) {
            return $this->error([], $e->getMessage());
        }
    }

    /**
     * 获取授权方的帐号基本信息
     * @param array $param
     */
    public function getAuthorizer($param = [])
    {
        try {
            $result = $this->app->getAuthorizer($param["authorizer_appid"]);
            if (isset($result['errcode']) && $result['errcode'] != 0) {
                return $this->error($result, $result["errmsg"]);
            }
            return $this->success($result);
        } catch (\Exception $e) {
            return $this->error([], $e->getMessage());
        }

    }
	
    /**
     * 授权回调事件响应 https://www.easywechat.com/docs/4.1/open-platform/server
     */
    public function server(){
        $server = $this->app->server;

        // component_verify_ticket
        $server->push(function ($message) {
            $component_verify_ticket = $message['ComponentVerifyTicket'];
            $verify_ticket = new VerifyTicket($this->app);
            $verify_ticket->setTicket($component_verify_ticket);
        }, Guard::EVENT_COMPONENT_VERIFY_TICKET);

        // 授权成功事件
        $server->push(function ($message) {
        }, Guard::EVENT_AUTHORIZED);

         // 授权取消事件
        $server->push(function ($message) {
            $appid = $message['AuthorizerAppid'];
            model('config')->update([ 'value' => ''], [ ['app_module', '=', 'shop'], ['config_key', 'in', ['WECHAT_CONFIG', 'WEAPP_CONFIG'] ], ['value', 'like', '%'. $appid .'%'], ['value', 'like', '%is_authopen%'] ]);
            Cache::tag("config")->clear();
        }, Guard::EVENT_UNAUTHORIZED);

        return $server->serve();
    }


    /**
     * 消息通知
     * @param $appid
     */
    public function message($appid){
        $officialAccount = $this->app(['authorizer_appid' => $appid, 'type' => 'wechat']);
//        $server = $officialAccount->server; // ❗️❗️  这里的 server 为授权方的 server，而不是开放平台的 server，请注意！！！
        $wechat_model = new Wechat(0);
        $wechat_model->app = $officialAccount;
        $wechat_model->relateWeixin();
    }


}